package com.common.data.desensitization.common.handler;

import com.common.data.desensitization.common.annotation.DesensitizationRule;
import com.common.data.desensitization.common.utils.RepeatMaskUtil;
import org.springframework.stereotype.Component;

@Component
public class DesensitizeEmailHandler implements DesensitizationHandler {
    @Override
    public String desensitize(String originalValue, DesensitizationRule rule) {
        // t***@example.com
        int atIndex = originalValue.indexOf('@');
        if (atIndex <= 0) return originalValue; // 非法邮箱格式
        if (atIndex <= 1) return rule.maskChar() + originalValue.substring(atIndex);
        if (atIndex <= 3) {
            return originalValue.charAt(0) + RepeatMaskUtil.repeatMask(atIndex - 1, rule.maskChar()) + originalValue.substring(atIndex);
        }
        return originalValue.substring(0, Math.min(3, atIndex-1)) + RepeatMaskUtil.repeatMask(Math.max(1, atIndex - Math.min(3, atIndex-1) -1), rule.maskChar()) + originalValue.charAt(atIndex-1) + originalValue.substring(atIndex);

    }
}
